// pages/tabBar1/components/grid1/grid1.js
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    my_schedule_file_url: '',
    targetHeight: 1700,
    targetWidth: 750,
    canvasShow: false
  },
  attached() {
    var that = this
    qq.getStorage({
      key: 'my_schedule_file_url',
      complete(res) {
        if (res.data) {
          that.setData({
            my_schedule_file_url: res.data
          })
        } else {
          that.getMyScheduleFileID()
        }
      }
    })
  },

  methods: {
    getMyScheduleFileID() {////////////去数据库中请求
      var that = this
      //console.log(app.globalData.access_token)
      //console.log(app.globalData.openid)
      qq.request({
        url: 'https://api.weixin.qq.com/tcb/databasequery?access_token=' + app.globalData.access_token,
        header: {
          'content-type': 'application/json' // 默认值
        }, method: "post",
        data: {
          "env": app.globalData.myEnv,
          "query": "db.collection(\"my_schedule\").where({_openid:\"" + app.globalData.openid + "\"}).get()"
        },
        success(res) {
          //console.log(res)
          if (res.data.data.length != 0) {
            //console.log(res)
            that.getMyScheduleFileUrl(JSON.parse(res.data.data[0]).my_schedule_file_id)/////////////调用获取url
            qq.setStorage({
              key: 'my_schedule_id',
              data: JSON.parse(res.data.data[0])._id
            })
          } else {
            //console.log(res.data.data)
          }
        }
      })
    },
    getMyScheduleFileUrl(fileid) {
      var that = this
      qq.request({
        url: 'https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json' // 默认值
        }, method: "post",
        data: {
          "env": app.globalData.myEnv,
          "file_list": [
            {
              "fileid": fileid,
              "max_age": 86400000//1000天
            }
          ]
        },
        success(res) {
          //console.log(2, res.data.file_list[0])
          var url = res.data.file_list[0].download_url
          that.setData({
            my_schedule_file_url: url
          })
          qq.setStorage({
            key: 'my_schedule_file_url',
            data: url
          }),
            qq.setStorage({
              key: 'my_schedule_file_id',
              data: res.data.file_list[0].fileid
            })
          // //console.log(that.data)
        }
      })
    },
    tap1() {
      // qq.navigateTo({
      //   url:"/pages/tabBar1/movie/movie"
      // })
      qq.showToast({
        icon: "none",
        title: '敬请期待'
      })
    },
    tap2() {
      var url = this.data.my_schedule_file_url
      if (url.length < 1) {
        qq.showToast({
          icon: 'none',
          title: "请长按上传哦~"
        })
      } else {
        qq.previewImage({
          current: url, // 当前显示图片的http链接
          urls: [url] // 需要预览的图片http链接列表
        })
      }
      //console.log("tap2")
    },
    longPress2() {
      //console.log("longpress")
      var that = this
      qq.chooseImage({
        count: 1,
        sourceType: ['album'],
        success(res) {
          //console.log(res)
          that.zipImg(res.tempFilePaths[0])
        }
      })
    },
    zipImg(tempFilePath) {
      var that = this
      qq.getImageInfo({
        src: tempFilePath,
        success(res) {
          //console.log(res)
          var targetHeight = res.height
          var targetWidth = res.width
          var maxWidth = 750
          var maxHeight = 2000 //2100以内 按宽度1000，高度自适应压缩，
          //console.log(targetHeight, targetWidth)

          if (targetWidth > maxWidth || targetHeight > maxHeight) {
            if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
              targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
              targetWidth = maxWidth;
              // //console.log(">") 顺序什么都不能改变，易错
            } else {
              targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
              targetHeight = maxHeight;
            }
          }
          //console.log(targetHeight, targetWidth)
          that.setData({
            targetWidth: targetWidth,
            targetHeight: targetHeight,
            canvasShow: true
          })
          setTimeout(function () {
            const ctx = qq.createCanvasContext('canvas',that);
            ctx.drawImage(tempFilePath, 0, 0, targetWidth, targetHeight);
            ctx.draw(false, function () {
              qq.canvasToTempFilePath({
                canvasId: ('canvas'),
                fileType: "jpg",
                quality: 0.6,
                destWidth: targetWidth,
                destHeight: targetHeight,
                success(res) {
                  //console.log(res)
                  that.deleteOldDB()
                  const filePath = res.tempFilePath
                  const cloudPath = 'my_schedule/' + app.globalData.openid+filePath.match(/\.[^.]+?$/)[0]
                  that.uploadFile(filePath, cloudPath)
                  that.setData({
                    canvasShow: false
                  })
                }
              },that)
            })
          }, 100)
        }
      })
    },

    uploadFile(filePath, cloudPath) { ///////////////////////////上传1张图片
      qq.showLoading({
        title: "上传中"
      })
      var that = this
      //console.log(filePath, cloudPath)
      var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
      //console.log(url)
      qq.request({////////////////////////获取cos的url
        url,
        header: {
          'content-type': 'application/json' // 默认值
        },
        data: {
          "env": app.globalData.myEnv,
          "path": cloudPath
        },
        method: "POST",
        success(res) {//////////////////////////通过cos上传
          //console.log(1, res)
          qq.uploadFile({
            url: res.data.url,
            filePath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"//记得设置
            },
            formData: {
              key: cloudPath,
              "Signature": res.data.authorization,
              "x-cos-security-token": res.data.token,
              "x-cos-meta-fileid": res.data.cos_file_id
            },
            success(res2) { ////////////////////添加到数据库
              //console.log(res2)
              that.getMyScheduleFileUrl(res.data.file_id)/////////上传到云存储之后才能去获得下载链接（res的，不是res2）
              var data = {
                _openid: app.globalData.openid,
                my_schedule_file_id: res.data.file_id
              }
              that.addToDB(JSON.stringify(data))
              //console.log(data)
            }, fail(msg) {
              //console.log(msg)
            }
          })
          //console.log(res)
        }
      })
    },

    addToDB(data) {
      qq.request({
        url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json' // 默认值
        }, method: "post",
        data: {
          "env": app.globalData.myEnv,
          "query": "db.collection(\"my_schedule\").add({\
            data: "+ data + "\
        })"
        },
        success(res) {
          qq.hideLoading()
          qq.showToast({
            title: "上传成功"
          })
          qq.setStorage({
            key: 'my_schedule_id',
            data: res.data.id_list[0]
          })
          //console.log(res.data)
        },fail(){
          qq.hideLoading()
          qq.showToast({
            icon:'none',
            title:'请检查网络'
          })
        }
      })
    },
    deleteOldDB() {
      qq.getStorage({
        key: 'my_schedule_id',
        success(res) {
          qq.request({
            url: 'https://api.weixin.qq.com/tcb/databasedelete?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
            header: {
              'content-type': 'application/json' // 默认值
            }, method: "post",
            data: {
              "env": app.globalData.myEnv,
              "query": "db.collection(\"my_schedule\").where({_id:\"" + res.data + "\"}).remove()"
            },
            success(res) {
              //console.log(res.data)
            }
          })
        }
      })
    },
    // deleteOldFile() { /////////自动替换
    //   qq.getStorage({
    //     key: 'my_schedule_file_id',
    //     success(res) {
    //       var fileid = res.data
    //       qq.request({
    //         url: 'https://api.weixin.qq.com/tcb/batchdeletefile?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
    //         header: {
    //           'content-type': 'application/json' // 默认值
    //         }, method: "post",
    //         data: {
    //           "env": app.globalData.myEnv,
    //           "fileid_list": [
    //             fileid
    //           ]
    //         },
    //         success(res) {
    //           //console.log(res.data)
    //         }
    //       })
    //     }
    //   })
    // },

    tap3() {
      //console.log("tap3")
      qq.navigateTo({
        url: '/pages/tabBar1/study_room/study_room',
        fail: function (res) {
          //console.log(res)
        }
      })
    },
    tap4() {
      qq.navigateTo({
        url: '/pages/tabBar1/love/love'
      })
    }
  }
})
